package com.pc.scrs.service.impl;

import com.pc.scrs.bean.po.Users;
import com.pc.scrs.dao.UsersDao;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
@Transactional
public class LoginDetailService implements UserDetailsService {

    @Resource
    private UsersDao usersDao;

    /**
     * spring security的登录认证业务
     * @param username 获得用户在登录页面输入的帐号
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Users users = usersDao.selectUserByUserName(username);
        List<String> permList = users.getPermList();
        String authorityList = String.join(",", permList);
        if(users!=null && users.getStatus()!=2){
            return new User(users.getUsername(),
                    users.getPassword(),
                    true,//账号可用
                    true,//账号未过期
                    true,//密码未过期
                    true,//账号未锁定
                    AuthorityUtils.commaSeparatedStringToAuthorityList(authorityList));
        }
        //将users对象转为spring security的user对象
        return new User(users.getUsername(), users.getPassword(), AuthorityUtils.commaSeparatedStringToAuthorityList(authorityList));
    }
}
